package demo2;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

@SuppressWarnings({"all"})
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp="";
    private int serverPort=0;
    public UdpEchoClient(String ip,int port) throws SocketException {
        //创建对象，但是不要手动指定端口
        socket=new DatagramSocket();
        /**
         * 因为我们的这个UDP协议不会保存对方的信息，，因此在我们的这个里面需要把ip信息记录下来
         */
        serverIp=ip;
        serverPort=port;
    }
    public void start() throws IOException {
        System.out.println("客户端启动！！！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("->");
            String request=scanner.next();
            //把请求内容构建对象，发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //把响应转换为字符串，打印输出
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("192.168.190.1",9090);
        client.start();
    }
}
